package com.ibpd.henuocms.web.controller.ext;
import java.lang.reflect.Field;
/**
 * 自定义的spring参数拦截处理器，用来实现类似struts2中的obj.prop参数封装的方式
 */
import java.util.Iterator;

import org.springframework.beans.BeanUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

import com.ibpd.henuocms.web.controller.manage.BaseController;
public class IbpdMethodArgumentsResolver implements WebArgumentResolver {
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(FormModel.class);
	}
	public Object resolveArgument(MethodParameter parameter, NativeWebRequest webRequest)
			throws Exception {
		if(!supportsParameter(parameter)) 
			return UNRESOLVED;
		String objName = parameter.getParameterName() + ".";
		Object o = BeanUtils.instantiate(parameter.getParameterType());
		StringBuffer tmp;
		String[] val;
		Field[] frr = parameter.getParameterType().getDeclaredFields();
		for (Iterator<String> itr = webRequest.getParameterNames(); itr.hasNext();) {
			tmp = new StringBuffer(itr.next());
			if (tmp.indexOf(objName) < 0)
				continue;
			BaseController base=new BaseController();
			for (int i = 0; i < frr.length; i++) {
				frr[i].setAccessible(true);
				if (tmp.toString().equals(objName + frr[i].getName())) {
					val = webRequest.getParameterValues(tmp.toString());
					frr[i].set(o, base.getValue(val[0],o.getClass().getMethod("get"+frr[i].getName().substring(0,1).toUpperCase()+frr[i].getName().substring(1), new Class[]{}).getReturnType().getSimpleName()));
				}
			}
		} 
		return o;
	}
}